package com.phonebook.interceptor;

import com.phonebook.entity.CheckResult;
import com.phonebook.entity.ResponseResult;
import com.phonebook.enums.CheckResultEnum;
import com.phonebook.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SysInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //解决复杂跨域请求
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        log.info("请求api：" + request.getRequestURI());
        if(request.getRequestURI().indexOf("image") == 1 || request.getRequestURI().endsWith(".js") || request.getRequestURI().endsWith(".css")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = request.getHeader("token");
        log.info("签名为{}",token);

        if (StringUtils.isEmpty(token)) {
            log.info("签名签证不存在");
            print(response, ResponseResult.error(CheckResultEnum.NULL.getCode(), CheckResultEnum.NULL.getMessage()));
            return false;
        }
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (!checkResult.isSuccess()) {
            switch (CheckResultEnum.getJwtEnumByCode(checkResult.getErrCode())) {
                case FAIL:
                    log.info("签名验证不通过");
                    print(response, ResponseResult.error(CheckResultEnum.FAIL.getCode(), CheckResultEnum.FAIL.getMessage()));
                    break;
                case EXPIRE:
                    log.info("签名验证过期");
                    print(response, ResponseResult.error(CheckResultEnum.EXPIRE.getCode(), CheckResultEnum.EXPIRE.getMessage()));
                    break;
                default:
            }
            return false;
        }
        log.info("签名验证通过");
        return true;
    }

    private void print(HttpServletResponse response, Object message) {
        try {
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            PrintWriter writer = response.getWriter();
            writer.write(message.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
